package puyu.manage.service.security.service;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import puyu.manage.service.SysUser.dao.SysUserMapper;
import puyu.manage.service.constant.Constants;
import puyu.manage.service.utils.except.BaseException;
import puyu.manage.service.utils.except.CustomException;


import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;


@Component
public class AppLogin extends DefaultCommonLogin {

    @Autowired(required = false)
    private AuthenticationManager authenticationManager;
    @Autowired(required = false)
    private SysUserMapper sysUserMapper;


    /**
     * 验证是否是手机号
     */
    private static final String PHONE = "^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$";

    @Override
    public Map<String, Object> login(Map<String, Object> params) {
        String userName = params.get("userName")+"";
        String passWord = params.get("password")+"";
        Map<String, Object> map = new HashMap<>(4);
        boolean flag = Pattern.compile(PHONE).matcher(userName).matches();
        Map<String, Object> sysUser = flag ? sysUserMapper.selectUserByPhone(userName) :
                sysUserMapper.selectUserInfoByUserName(userName);
        if (ObjectUtil.isNull(sysUser)) {
            throw new BaseException("对不起，您输入的的用户名不存在。请重新再试！");
        }

        // 验证用户
        Authentication authentication = null;
        map = authentication(authentication, userName, passWord, null);
        //  登陆超时
        Map<String, Object> overTimeMap = loginOverTime((Authentication) map.get("authentication"),
                userName, Constants.MOIBLE);
        if (MapUtils.isNotEmpty(overTimeMap)) {
            map.putAll(overTimeMap);
        }

        return map;
    }

    @Override
    public Map<String, Object> authentication(Authentication authentication, String username, String password, Integer loginNum) {
        Map<String, Object> map = new HashMap<>();
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
            map.put("authentication", authentication);
            return map;
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new BaseException("用户密码不正确或不符合规范异常类");
            } else {
                throw new CustomException(e.getMessage());
            }
        }
    }
}
